import 'dart:convert';
import 'dart:io';

import 'package:demo/config/build_config.dart';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart';
import 'package:flutter/foundation.dart';

import 'interceptors/logger.dart';
import 'interceptors/request_before.dart';
import 'interceptors/response_after.dart';

/// 网络请求
class HttpClientDio extends DioForNative {
  /// 工厂模式
  factory HttpClientDio() => _getInstance();

  /// 单利
  static HttpClientDio get instance => _getInstance();
  static HttpClientDio? _instance;

  HttpClientDio._internal() {
    (httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
      final String httpHost = BuildConfig.shared.httpProxyClientHost;
      // 配置代理
      if (httpHost.isNotEmpty) {
        client.findProxy = (uri) {
          return 'PROXY $httpHost';
        };
        // 代理工具会提供一个抓包的自签名证书，会通不过证书校验，所以我们禁用证书校验
        client.badCertificateCallback = (X509Certificate cert, String host, int port) => true;
      }
      return client;
    };
    (transformer as DefaultTransformer).jsonDecodeCallback = _parseJson;
    options = BaseOptions(connectTimeout: 5000, receiveTimeout: 30000, sendTimeout: 30000);
    interceptors.addAll([
      RequestBeforeInterceptors(),
      LoggerInterceptors(),
      ResponseAfterInterceptors(),
    ]);
  }

  static HttpClientDio _getInstance() => _instance ??= HttpClientDio._internal();
}

/// 解析json
_parseJson(String text) => compute(_parseAndDecode, text);

_parseAndDecode(String response) => jsonDecode(response);
